import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/admin',
      component: () => import('../views/admin/AdminLayout.vue'),
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'admin-dashboard',
          component: () => import('../views/admin/DashboardView.vue')
        },
        {
          path: 'elderly',
          name: 'admin-elderly',
          component: () => import('../views/admin/ElderlyManagement.vue')
        },
        {
          path: 'health',
          name: 'admin-health',
          component: () => import('../views/admin/HealthRecords.vue')
        },
        {
          path: 'appointments',
          name: 'admin-appointments',
          component: () => import('../views/admin/AppointmentManagement.vue')
        },
        {
          path: 'staff',
          name: 'admin-staff',
          component: () => import('../views/admin/StaffManagement.vue')
        }
      ]
    },
    {
      path: '/user',
      component: () => import('../views/user/UserLayout.vue'),
      redirect: '/user/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'user-dashboard',
          component: () => import('../views/user/UserDashboard.vue')
        },
        {
          path: 'profile',
          name: 'user-profile',
          component: () => import('../views/user/UserProfile.vue')
        },
        {
          path: 'health',
          name: 'user-health',
          component: () => import('../views/user/UserHealth.vue')
        },
        {
          path: 'appointments',
          name: 'user-appointments',
          component: () => import('../views/user/UserAppointments.vue')
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userInfo = localStorage.getItem('userInfo')
  
  if (to.path === '/login') {
    next()
  } else if (!userInfo) {
    next('/login')
  } else {
    const user = JSON.parse(userInfo)
    
    // 检查用户角色权限
    if (to.path.startsWith('/admin') && user.role !== 'admin') {
      next('/user')
    } else if (to.path.startsWith('/user') && user.role !== 'user') {
      next('/admin')
    } else {
      next()
    }
  }
})

export default router
